import glslcode from './src/code.glsl';

declare let amdRequire: any;

let monacoEditor: monaco.editor.IStandaloneCodeEditor;
let monacoEditor1: monaco.editor.IStandaloneCodeEditor;

initMonaco(async () =>
{
    await initcompile();

    showShader();
});

function showShader()
{
    showCode(glslcode);
    showCode1(glslcode);
}

function initMonaco(callback: () => void)
{
    //
    amdRequire.config({ paths: { vs: 'monaco-editor/min/vs' } });
    amdRequire(['vs/editor/editor.main'], () =>
    {
        monacoEditor = monaco.editor.create(document.getElementById('container'), {
            model: null,
            formatOnType: true,
        });
        monacoEditor1 = monaco.editor.create(document.getElementById('container1'), {
            model: null,
            formatOnType: true,
        });
        window.onresize = function ()
        {
            monacoEditor.layout();
            monacoEditor1.layout();
        };
        callback();
    });
}

function showCode(code: string)
{
    const oldModel = monacoEditor.getModel();
    const newModel = monaco.editor.createModel(code, 'glsl');
    monacoEditor.setModel(newModel);
    if (oldModel) oldModel.dispose();

    monacoEditor.onDidChangeModelContent(() =>
    {
        const newcode = monacoEditor.getValue();
        showCode1(newcode);
    });
}

function showCode1(code: string)
{
    const result = window['glslup'](code);

    const oldModel = monacoEditor1.getModel();
    const newModel = monaco.editor.createModel(result.code, 'glsl');
    monacoEditor1.setModel(newModel);
    if (oldModel) oldModel.dispose();
}

async function initcompile()
{
    const p = new Promise((resolve) =>
    {
        const viewer = document.getElementById('viewer') as HTMLIFrameElement;
        viewer.src = './src/index.html';

        viewer.onload = async () =>
        {
            window['glslup'] = viewer.contentWindow['glslup'];

            resolve(0);
        };
    });

    return p;
}
